package com.dmagic.cms.service.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dmagic.cms.common.dao.CommonDao;
import com.dmagic.cms.common.exception.ServiceException;
import com.dmagic.cms.common.exception.ValidateException;
import com.dmagic.cms.common.query.PageUtil;
import com.dmagic.cms.common.service.CommonService;
import com.dmagic.cms.dao.AppUserDao;
import com.dmagic.cms.dao.PermissionDao;
import com.dmagic.cms.entity.AppUser;
import com.dmagic.cms.entity.Permission;
import com.dmagic.cms.service.AppUserService;
import com.google.common.collect.Lists;

/**
 * [ticket id] Description of the class
 * 
 * @author songlin.li @ Version : V<Ver.No> <2013-1-8>
 */
@Service
@Transactional(readOnly = true)
public class AppUserServiceImpl extends CommonService<AppUser> implements AppUserService {

	@Autowired
	private AppUserDao appUserDao;

	@Autowired
	private PermissionDao permissionDao;

	@Override
	protected CommonDao<AppUser, Serializable> getCommonDao() {
		return (CommonDao) appUserDao;
	}

	@Override
	public AppUser getAppUserByUserId(Long appUserId) {
		return super.getEntityById(appUserId);
	}

	@Override
	public AppUser getAppUserByUserName(String userName) throws Exception {
		return appUserDao.getAppUserByUserName(userName);
	}

	@Transactional(readOnly = false)
	@Override
	public void deleteUserById(Long appUserId) throws Exception {
		deleteEntityById(appUserId);
	}

	@Transactional(readOnly = false)
	@Override
	public void deleteUser(List<Long> userIds) throws ServiceException {
		for (Long appUserId : userIds) {
			deleteEntityById(appUserId);
		}
	}

	@Transactional(readOnly = false)
	@Override
	public void saveAppUser(AppUser entity) throws ValidateException {
		saveEntity(entity);
		/*List<AppUserPermission> userPermissions = Lists.newArrayList();
		for (Permission p : entity.getPermissions()) {
			AppUserPermission appUserPermission = new AppUserPermission();
			appUserPermission.setAppUserId(entity.getAppUserId());
			appUserPermission.setPermissionId(p.getPermissionId());
			// appUserPermissionDao.saveEntity(appUserPermission);
			userPermissions.add(appUserPermission);
		}
		appUserPermissionDao.batchSave(userPermissions);*/
	}

	@Override
	public void searchAppUser(PageUtil<AppUser> pageUtil) throws ServiceException {
		try {
			appUserDao.searchUser(pageUtil);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public List<Permission> getAllPermissions() {
		return permissionDao.getAll();
	}

}
